package com.lindroy.controller

import com.lindroy.config.PageResult
import com.lindroy.config.RespResult
import com.lindroy.constants.HTTP_OK
import com.lindroy.constants.ResultMsg
import com.lindroy.entity.Employee
import com.lindroy.repository.EmployeeRepo
import com.lindroy.service.EmployeeService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageRequest
import org.springframework.web.bind.annotation.*

/**
 * @author Lin
 * @date 2019/10/10
 * @function
 * @Description
 */
@RestController
@RequestMapping("/employee")
class EmployeeController {
    @Autowired
    lateinit var employeeService: EmployeeService

    lateinit var employeeRepo: EmployeeRepo

    @PostMapping("list")
    fun findByPage(pageNo: Int, pageSize: Int): RespResult {
        val pageRequest = PageRequest.of(pageNo, pageSize)
        val p: Page<Employee> = employeeService.findAll(pageRequest)
        return RespResult(HTTP_OK, ResultMsg.FIND_SUCCESS, PageResult<Employee>(
            list = p.content,
            size = p.size,
            last = p.isLast,
            totalElements = p.totalElements,
            totalPages = p.totalPages
        ))
    }


    @GetMapping("/employees")
//    @ResponseBody
    fun findAll(): RespResult = RespResult(HTTP_OK, "请求成功", employeeService.findAll())

    /* @DeleteMapping("/delete/{firstName}")
     @ResponseBody
     fun deleteByFirstName(@PathVariable( "firstName") firstName: String) {
         val employees = employeeService.findByFirstName(firstName)
         employeeService.deleteAll(employees as MutableIterable<Employee>)
     }*/

    @DeleteMapping("/employees/{id}")
//    @ResponseBody
    fun deleteById(@RequestParam @PathVariable("id") id: Int) = RespResult(HTTP_OK, "删除成功", employeeService.deleteById(id))

    @PostMapping("/add/{firstName}/{lastName}/{departmentId}")
    fun save(
        @PathVariable("firstName") firstName: String,
        @PathVariable(value = "lastName") lastName: String,
        @PathVariable(value = "departmentId") departmentId: Int
    ) =
        RespResult(
            HTTP_OK,
            "新增成功",
            employeeService.save(Employee(firstName = firstName, lastName = lastName, departmentId = departmentId, createTime = null))
        )

    @PostMapping("/insert")
    fun insert(@RequestBody employee: Employee): RespResult {
        employeeService.save(employee)
        return RespResult(HTTP_OK, "新增成功")
    }

    @PostMapping("/insertList")
    fun insert(@RequestBody employees: MutableList<Employee>): RespResult {
        employeeService.saveAll(employees)
        return RespResult(HTTP_OK, "新增成功")
    }

    @PostMapping("/update")
    fun update(@RequestBody employee: Employee) = RespResult(HTTP_OK, "修改成功", employeeService.save(employee))

}